<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>取消请求</title>
</head>
<body>
  <button onclick="getProducts1()">获取商品列表1</button><br>
  <button onclick="getProducts2()">获取商品列表2</button><br>
  <button onclick="cancelReq()">取消请求</button><br>

  <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
  <script>
    axios.defaults.baseURL = 'http://localhost:4000'
    let cancel; // 用于存储取消请求函数
    function getProducts1() {
      // 发送请求前先判断是否有cancel函数
      if(cancel) {
        cancel('强制取消')
      }

      axios('/getProducts1', {
        cancelToken: new axios.CancelToken((c) => { // 在cancelToken中同步执行
          cancel = c
        })
      }).then(
        response => {
          cancel = null
          console.log('1111 onRsolved()', response.data)
        },
        error => {
          if(axios.isCancel(error)) {
            console.log('2222 取消请求', error.message)
          } else {
            cancel = null
            console.log('2222 请求出错', error.message)
          }
        }
      )
    }

    function getProducts2() {
      // 发送请求前先判断是否有cancel函数
      if(cancel) {
        cancel('强制取消')
      }
      
      axios({
        url: '/getProducts2',
        cancelToken: new axios.CancelToken((c) => {
          cancel = c
        })
      }).then(
        response => console.log('2222 onRsolved()', response.data),
        error =>{
          if(axios.isCancel(error)) {
            console.log('2222 取消请求', error.message)
          } else {
            cancel = null // 出错的时候不需要调用取消请求函数
            console.log('2222 请求出错', error.message)
          }
        }
      )
    }

    function cancelReq() {
      if(cancel) {
        cancel('强制取消')
      }
    }
  </script>
</body>
</html>